package com.dayuanit.dy15.atm.controller;

import com.dayuanit.dy15.atm.dto.ResponseDTO;
import com.dayuanit.dy15.atm.service.UserService;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.apache.commons.codec.binary.Base64;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.UUID;

@Controller
@PropertySource("classpath:atm.properties")
public class UserDetailController extends BaseController {

    @Autowired
    private UserService userService;

    @Value("${avatar.file.path}")
    private String avatarFilePath;

    /**
     * 第一步 通过邮箱里的链接 访问此接口 并跳转到找回密码的页面
     * @param email
     * @param expireTime
     * @param sign
     * @return
     */
    @RequestMapping("/userDetail/toRetrievePassword.do")
    public String toRetrievePassword(String email, long expireTime, String sign, HttpSession session) {
        //因为在第二步 重置新密码的时候，需要验证当前人，那么就需要这三个参数，所以应该放在session中，
        //不能放在request中，request保存的东西只能在当前请求中使用，下一次请求就访问不到了。
        session.setAttribute("email", email);
        session.setAttribute("expireTime", expireTime);
        session.setAttribute("sign", sign);
        return "retrievePwd";
    }


    /**
     * 第二步：在找回密码的页面 输入新密码 进行密码的修改
     *
     * 但是有个问题：如何确认你是谁？你要修改谁的密码？
     * 我们是通过邮箱来找回密码，那么就要看谁绑定了这个邮箱。
     * 如何确认此邮箱是你绑定的？只能通过签名校验。
     * @param password
     * @param confirmPwd
     * @return
     */
    @RequestMapping("/userDetail/retrievePwd.do")
    @ResponseBody
    public ResponseDTO retrievePwd(String password, String confirmPwd, HttpSession session) {

        String email = (String)session.getAttribute("email");
        long expireTime = (long)session.getAttribute("expireTime");
        String sign = (String)session.getAttribute("sign");

        userService.retrievePwd(email, sign, expireTime, password, confirmPwd);
        return ResponseDTO.sucess();
    }


    /**
     * 405 – Method Not Allowed  当以get方式请求的时候，则返回405
     * @param username
     * @return
     */
    @RequestMapping(value = "/userDetail/uploadAvatar.do")
    @ResponseBody
    public ResponseDTO uploadAvatar(String username, MultipartFile avatarFile, HttpServletRequest request) throws Exception {
        System.out.println("username=" + username);

        if (!avatarFile.isEmpty()) {
            byte[] bytes = avatarFile.getBytes();
            System.out.println("文件大小=" + bytes.length);

            //方案一：
//            try ( FileOutputStream fileOutputStream = new FileOutputStream("/hanhan666666666666.jpg");) {
//                fileOutputStream.write(bytes);
//                fileOutputStream.flush();
//            }

            String filePath = avatarFilePath + getUserId(request);
            //方案二：
//            avatarFile.transferTo(new File(filePath));

            saveToMongodb(bytes,  "avatar" + getUserId(request));

//            String s = new String(bytes);
//            System.out.println(s);

            String s1 = Base64.encodeBase64String(bytes);
            System.out.println(s1);

            byte[] bytes1 = Base64.decodeBase64(s1);
            System.out.println("bytes1=" + bytes1.length);


        }

        return ResponseDTO.sucess();
    }


    /**
     * 查看我的头像
     * @return
     */
    @RequestMapping(value = "/userDetail/showAvatar.do")
    public void showAvatar(HttpServletResponse response, HttpServletRequest request) {
        //TODO 到磁盘里找到用户的头像图片，然后将其读取到内存中，再通过输出流将其输出到客户端展示即可。

        String filePath = avatarFilePath + getUserId(request);

//        try (FileInputStream fileInputStream = new FileInputStream(filePath);) {
//            byte[] buf = new byte[1024];
//            int length = -1;
//            while (-1 != (length = fileInputStream.read(buf))) {
//                OutputStream out = response.getOutputStream();
//                out.write(buf, 0, length);
//                out.flush();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        try {
            MongoClient mongoClient = new MongoClient("192.168.5.178", 27017);
            MongoDatabase database = mongoClient.getDatabase("atm-avatar");

            GridFSBucket bucket = GridFSBuckets.create(database);

            String filName = UUID.randomUUID().toString();
            // 下载
            bucket.downloadToStream("avatar" + getUserId(request), response.getOutputStream());
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void saveToMongodb(byte[] data, String fileName) {
        try {
            MongoClient mongoClient = new MongoClient("192.168.5.178", 27017);
            MongoDatabase database = mongoClient.getDatabase("atm-avatar");

            GridFSBucket bucket = GridFSBuckets.create(database);

            // 上传
            ObjectId fileId = bucket.uploadFromStream(fileName, new ByteArrayInputStream(data));
            System.out.println("上传完成。 文件ID："+fileId);
            System.out.println("上传完成。 文件名称："+fileName);

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
